
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.net.*;
import java.io.*;

public class Logo extends JApplet implements ActionListener {
	
	private JDesktopPane desktop;
	private JInternalFrame JIFedit,JIFexec,JIFconsol;
	private JCheckBoxMenuItem JCBMediteur,JCBMexecution,JCBMconsole,JCBtelecommande;
	private JMenuItem itemNouveau,itemOpen,itemSave,itemSaveAs,itemExit,itemCopy,itemCut,itemPaste,itemInfo,itemVersion;
	private JMenuItem itemUndo,itemRedo,itemSearch;
	private Editeur edit;
	private Execution exec;
	private Console consol;
	private Bibliotheque biblio;
	private String TitreEditeur = "Editeur";
	public static Image Iturtle,enregistrer,IzoomM,IzoomP,Ianimal,IhautparleurOn,IhautparleurOff;
	private boolean saved = false;
	//telecommande allumer
	private boolean telecommandeOn = false;
	private JToolBar barreO;
	private JToolBar barreO2;
	private JButton Bsave,BzoomM,BzoomP,Bhautparleur,Banimal,Btelecommande,BImprimante,BUndo,BRedo;
	private JComboBox Cvitesse,CZoom,Couleur;
	private ImageIcon[] images;
	private Image[] image;
	private Telecommande telecommande;
	private Font fondToolBar;
	public static int zoom = 1;
	public static boolean sonOn = true;
		
	public void init() {
		
		JIFedit = new JInternalFrame(TitreEditeur+"- Nouveau fichier",true,false,true,true);
		JIFexec = new JInternalFrame("Execution",true,false,true,true);
		JIFconsol = new JInternalFrame("Console",true,false,true,true);
		
		//Chargement Image
		File img= new File("tortue.png");
		File img2= new File("imageToolbar/enregistrer.gif");
		File img3= new File("imageToolbar/animalTortue.gif");
		File img4= new File("imageToolbar/zoomM.png");
		File img5= new File("imageToolbar/zoomP.png");
		File img6= new File("imageToolbar/hautparleur.gif");
		//Chargement image comboCouleur
		File img7= new File("imageToolbar/carreBlanc.gif");
		File img8= new File("imageToolbar/carreBleu.gif");
		File img9= new File("imageToolbar/carreJaune.gif");
		File img10= new File("imageToolbar/carreNoir.gif");
		File img11= new File("imageToolbar/carreRouge.gif");
		File img12= new File("imageToolbar/carreVert.gif");
		File img14= new File("imageToolbar/hautparleurOff.gif");
		
		try {
			Iturtle = ImageIO.read(img);
			enregistrer = ImageIO.read(img2);
			Ianimal = ImageIO.read(img3);
			IzoomM = ImageIO.read(img4);
			IzoomP = ImageIO.read(img5);
			IzoomP = ImageIO.read(img5);
			IhautparleurOn = ImageIO.read(img6);
			IhautparleurOff = ImageIO.read(img14);
			//palette couleur
			image = new Image[6];
			image[0]= ImageIO.read(img7);
			image[1]= ImageIO.read(img8);
			image[2]= ImageIO.read(img9);
			image[3]= ImageIO.read(img10);
			image[4]= ImageIO.read(img11);
			image[5]= ImageIO.read(img12);
			
			} catch (IOException e) {
			e.printStackTrace();
			}
			
		barreO = new JToolBar();
		barreO2 = new JToolBar();
		barreO.setBackground(new Color(240,240,240));
		barreO2.setBackground(new Color(240,240,240));
		Btelecommande = new JButton();
		Btelecommande.setIcon(new ImageIcon("imageToolbar/telecommande.png"));
		Btelecommande.addActionListener(this);
		Btelecommande.setBorderPainted(false);
		BImprimante = new JButton();
		BImprimante.setIcon(new ImageIcon("imageToolbar/imprimante.png"));
		BImprimante.addActionListener(this);
		BImprimante.setBorderPainted(false);
		BUndo = new JButton();
		BUndo.setIcon(new ImageIcon("imageToolbar/undo.png"));
		BUndo.addActionListener(this);
		BUndo.setBorderPainted(false);
		BRedo = new JButton();
		BRedo.setIcon(new ImageIcon("imageToolbar/redo.png"));
		BRedo.addActionListener(this);
		BRedo.setBorderPainted(false);
		
		
		barreO.add(Btelecommande);
		barreO.add(BImprimante);
		barreO.add(BUndo);
		barreO.add(BRedo);
		barreO.add(Box.createRigidArea(new Dimension(90, 0))); //espace boutons JToolBar
		Bsave = new JButton();
		Bsave.setIcon(new ImageIcon(enregistrer));
		Bsave.addActionListener(this);
		Bsave.setBorderPainted(false);
		Banimal = new JButton();
		Banimal.setIcon(new ImageIcon(Ianimal));
		Banimal.setBorderPainted(false);
		Banimal.addActionListener(this);
		BzoomM = new JButton();
		BzoomM.setIcon(new ImageIcon(IzoomM));
		BzoomM.setBorderPainted(false);
		BzoomP = new JButton();
		BzoomP.setIcon(new ImageIcon(IzoomP));
		BzoomP.setBorderPainted(false);
		BzoomP.addActionListener(this);
		Bhautparleur = new JButton();
		Bhautparleur.setIcon(new ImageIcon(IhautparleurOn));
		Bhautparleur.setBorderPainted(false);
		Bhautparleur.addActionListener(this);
		
		//on definit un style		
		fondToolBar = new Font("Arial",Font.BOLD,10);
		
		//combobox vitesse
		String choixVitesse[] = {"Lent","Normal","Rapide"};
		Cvitesse = new JComboBox(choixVitesse);		
		Cvitesse.setBorder(BorderFactory.createTitledBorder(null,"Vitesse",0,0,fondToolBar));
		
		//JTextField zoom
		CZoom = new JComboBox();
		CZoom.setEditable(true);
		CZoom.setBorder(BorderFactory.createTitledBorder(null,"Zoom",0,0,fondToolBar));
		CZoom.setPreferredSize(new Dimension(50,35));	
		//on definit la comboBox associe a la couleur du fond
		images = new ImageIcon[image.length];
        Integer[] intArray = new Integer[image.length];
        for (int i = 0; i < image.length; i++) {
            intArray[i] = new Integer(i);
            images[i] = new ImageIcon(image[i]);          
        }
        
             
        Couleur = new JComboBox(intArray);
        ComboBoxRenderer renderer= new ComboBoxRenderer();
        
        Couleur.setRenderer(renderer);
        Couleur.setMaximumRowCount(6);
        Couleur.setBorder(BorderFactory.createTitledBorder(null,"Couleur fond",0,0,fondToolBar));
		
		
		//ajout des boutons
		barreO2.add(Bsave);
		barreO2.add(Banimal);
		barreO2.add(Cvitesse);		
		barreO2.add(BzoomM);
		barreO2.add(BzoomP);
		barreO2.add(CZoom);
		barreO2.add(Couleur);
		barreO2.add(Bhautparleur);
		
		
		barreO.add(barreO2);
		
				
		exec = new Execution();
		consol = new Console(this);
		biblio = new Bibliotheque(this);
		edit = new Editeur(JIFedit,biblio);	
		this.add(barreO,BorderLayout.NORTH);
		this.AddMenu();		
		this.AddDesktop();		
	}
	
	public Bibliotheque getBiblio(){return biblio;}
	public Console getConsol(){return consol;}
	public Editeur getEdit(){return edit;}
	public Execution getExec(){return exec;}
	
	private void AddDesktop(){				
		desktop = new JDesktopPane();								
		
		this.getContentPane().add(desktop, BorderLayout.CENTER);
		desktop.setBackground(Color.LIGHT_GRAY);
		desktop.add(JIFedit, JLayeredPane.DEFAULT_LAYER);
		desktop.add(JIFexec, JLayeredPane.DEFAULT_LAYER);
		desktop.add(JIFconsol, JLayeredPane.DEFAULT_LAYER);		
		
		int HautScreen = (int) this.getSize().getHeight();
		int LargScreen = (int) this.getSize().getWidth();
		
		//on affiche l'editeur
		JIFedit.getContentPane().add(edit);
		JIFedit.setSize(LargScreen/3, HautScreen-80);
		JIFedit.setLocation(1, 1);
		JIFedit.setVisible(true);
		
		JIFexec.getContentPane().add(exec,"Center");
		JIFexec.setBounds(JIFedit.getWidth()+10,1,LargScreen-JIFedit.getWidth()-10,HautScreen*3/4-55) ;
		JIFexec.setVisible(true);
		
		
		JIFconsol.getContentPane().add(consol,"Center");									
		JIFconsol.setBounds(JIFedit.getWidth()+10,exec.getHeight()+30,LargScreen-JIFedit.getWidth()-10,HautScreen-exec.getHeight()-110);
		JIFconsol.setVisible(true);
	}
	
	private void AddMenu(){
		JMenuBar menuBar = new JMenuBar();
		
		JMenu menuFichier = new JMenu("Ficher");
		JMenu menuEdition = new JMenu("Edition");
		JMenu menuAffichage = new JMenu("Affichage");
		JMenu menuAide = new JMenu("Aide");
		
		itemNouveau = new JMenuItem("Nouveau");	
		itemOpen = new JMenuItem("Ouvrir...");			    
		itemSave = new JMenuItem("Enregistrer");
		itemSaveAs = new JMenuItem("Enregistrer sous...");
		itemExit = new JMenuItem("Fermer");
		itemNouveau.addActionListener(this);
		itemOpen.addActionListener(this);
		itemSave.addActionListener(this);		
		itemSaveAs.addActionListener(this);
		
		
		itemUndo = new JMenuItem("Annuler");
		itemRedo = new JMenuItem("Refaire");
		itemCopy = new JMenuItem("Copier");
		itemCut = new JMenuItem("Couper");
		itemPaste = new JMenuItem("Coller");
		itemSearch = new JMenuItem("Rechercher");
		
		JCBMediteur = new JCheckBoxMenuItem("Editeur",true);
		JCBMexecution = new JCheckBoxMenuItem("Execution",true);
		JCBMconsole = new JCheckBoxMenuItem("Console",true);
		JCBtelecommande = new JCheckBoxMenuItem("Telecommande",false);
		JCBMediteur.addActionListener(this);
		JCBMexecution.addActionListener(this);
		JCBMconsole.addActionListener(this);
		JCBtelecommande.addActionListener(this);
		
		itemInfo = new JMenuItem("Qu'est ce que le LOGO ?");	    
		itemVersion = new JMenuItem("Version");
		itemInfo.addActionListener(this);
		itemVersion.addActionListener(this);
		
		this.setJMenuBar(menuBar);	    
		menuBar.add(menuFichier);
		menuBar.add(menuEdition);
		menuBar.add(menuAffichage);
		menuBar.add(menuAide);	       	    
		menuFichier.add(itemNouveau);
		menuFichier.addSeparator();
		menuFichier.add(itemOpen);
		menuFichier.add(itemSave);
		menuFichier.add(itemSaveAs);
		menuFichier.addSeparator();
		//menuFichier.add(itemExit);
		
		menuEdition.add(itemUndo);
		menuEdition.add(itemRedo);
		menuEdition.addSeparator();
		menuEdition.add(itemCopy);
		menuEdition.add(itemCut);
		menuEdition.add(itemPaste);
		menuEdition.addSeparator();
		menuEdition.add(itemSearch);
		menuAffichage.add(JCBMediteur);
		menuAffichage.add(JCBMexecution);
		menuAffichage.add(JCBMconsole);
		menuAffichage.addSeparator();
		menuAffichage.add(JCBtelecommande);
		
		menuAide.add(itemInfo);
		menuAide.add(itemVersion);	   		
	}
	
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == JCBMediteur) {JIFedit.setVisible(!JIFedit.isVisible());}
		if (e.getSource() == JCBMexecution) {JIFexec.setVisible(!JIFexec.isVisible());}
		if (e.getSource() == JCBMconsole) {JIFconsol.setVisible(!JIFconsol.isVisible());}
		if (e.getSource() == JCBtelecommande) {demarrerTelecommande();}
		if (e.getSource() == itemNouveau) 
		
		{
			if (edit.isModif())
			{
				int retour = 
				JOptionPane.showConfirmDialog(this,
			              "Enregistrer les modifications du fichier avant de le fermer ?",
			              "Nouveau fichier",
			              JOptionPane.YES_NO_CANCEL_OPTION);
				if (retour==JOptionPane.OK_OPTION)
					{this.enregistrer();this.nouveau();}
				else if (retour==JOptionPane.NO_OPTION)
					{this.nouveau();}
			}			
		}
		if (e.getSource() == itemOpen) {this.ouvrir();} //edit.lecture("aParser.txt");
		if (e.getSource() == itemSaveAs) {this.enregistrerSous();}
		if (e.getSource() == itemSave) {this.enregistrer();}
		if (e.getSource() == itemVersion) 
		{
			JOptionPane.showMessageDialog(this,"Interpreteur LOGO : version 0.1 \n\n" +
					"Auteurs : \n" +
					"\t - Delfour Kevin \n" +
					"\t - Allier Simon \n" +
					"\t - Lalluque Renaud \n" +
					"\t - Grollemund Naitan \n",
					"Interpreteur Logo",
					JOptionPane.INFORMATION_MESSAGE);
		}
		if (e.getSource() == itemInfo)
		{			
			URL recup;
			try {
				recup = new URL(getDocumentBase(), "http://lwh.free.fr/pages/prog/logo/Logo.pdf");
				this.getAppletContext().showDocument(recup, "_blank");
			} catch (MalformedURLException netException) {
				JOptionPane.showMessageDialog(this,
						"Impossible d'acceder a la documentation, verifier votre acces internet",
						"Erreur",
						JOptionPane.ERROR_MESSAGE);													
			}		
		}	
		
		if(e.getSource()==Btelecommande){
			
			demarrerTelecommande();
			consol.out("telecommande on");
		}
		
		if(e.getSource()==Bsave){
			
			exec.Enregistrer();
			consol.out("image enregistree");	
		}
		
		if(e.getSource()==Banimal){
			consol.out("affichage animal");
		}
		
		if(e.getSource()==BzoomP){
			consol.out("zoom +");
			zoom=2;
		}
		
		if(e.getSource()==Bhautparleur){
			if(sonOn)
			{Bhautparleur.setIcon(new ImageIcon(IhautparleurOff));
			 sonOn=false;
			 consol.out("hautparleur off");
			}
			else
			{Bhautparleur.setIcon(new ImageIcon(IhautparleurOn));
			 sonOn=true;
			 consol.out("hautparleur on");
			}
		}
		
	}
	
	
	private void demarrerTelecommande() {
		if(!telecommandeOn)
			telecommande = new Telecommande(edit);
		telecommandeOn=true;
		
	}


	File currentPath = (new JFileChooser()).getCurrentDirectory(); //new File(System.getProperty("user.dir"));
	String currentFile;
	FiltreFichier FFLogo = new FiltreFichier( new String[]{"logo"},"Document Logo (*.logo)");
	FiltreFichier FFText = new FiltreFichier( new String[]{"txt"},"Document texte (*.txt)"); 
	
	public void ouvrir()
	{
		JFileChooser choix = new JFileChooser();
		choix.setCurrentDirectory(currentPath);		
		choix.addChoosableFileFilter(FFText);
		choix.addChoosableFileFilter(FFLogo);
		int retour = choix.showOpenDialog(getParent());
		if(retour == JFileChooser.APPROVE_OPTION) {			
			currentFile = choix.getSelectedFile().getAbsolutePath(); 
			currentPath = choix.getSelectedFile().getAbsoluteFile();			
			JIFedit.setTitle(TitreEditeur+" - "+choix.getSelectedFile().getName());
			edit.lecture(currentFile); //ouverture du fichier
			edit.setModif(false); //on reinitialise l'indicice de modification
			consol.out("Ouverture du fichier : "+currentFile);
		}
		else ;  	
	}
	public void enregistrerSous()
	{
		JFileChooser choix = new JFileChooser();
		choix.setCurrentDirectory(currentPath);
		choix.addChoosableFileFilter(FFText);
		choix.addChoosableFileFilter(FFLogo);
		int retour = choix.showSaveDialog(getParent());
		if(retour == JFileChooser.APPROVE_OPTION) {			
			currentFile = choix.getSelectedFile().getAbsolutePath(); //sauvegarde du fichier
			currentPath = choix.getSelectedFile().getAbsoluteFile();
			choix.setCurrentDirectory(currentPath.getParentFile());
			JIFedit.setTitle(TitreEditeur+" - "+choix.getSelectedFile().getName());
			edit.ecrire(currentFile);
			edit.setModif(false); //on reinitialise l'indicice de modification
			consol.out("Fichier enregistr� : "+currentFile);
		}
		else ;
	}
	
	public void enregistrer()	
	{
		if (saved) 
		{
			edit.ecrire(currentFile);
			if (edit.isModif())
			{
				JIFedit.setTitle(JIFedit.getTitle().substring(0,JIFedit.getTitle().length()-1));
				consol.out("Fichier enregistr� : "+currentFile);
			}
		}
		else {this.enregistrerSous();saved=true;}		
	}
	
	public void nouveau()
	{
		edit.nouveau();
		JIFedit.setTitle(TitreEditeur+"- Nouveau fichier");
		edit.setModif(false);
		consol.out("Creation d'un nouveau fichier");
	}
	
	public String lireMessage(String typeMessage) 
	{
		String retour = JOptionPane.showInputDialog(typeMessage);
		return retour;
	}
	
	class ComboBoxRenderer extends JLabel implements ListCellRenderer 
 	{
        private Font uhOhFont;

        public ComboBoxRenderer() {
            setOpaque(true);
            setHorizontalAlignment(CENTER);
            setVerticalAlignment(CENTER);
        }

	public Component getListCellRendererComponent(
                                           JList list,
                                           Object value,
                                           int index,
                                           boolean isSelected,
                                           boolean cellHasFocus) {
         
           int selectedIndex = ((Integer)value).intValue();


            if (isSelected) {
                setBackground(list.getSelectionBackground());                
                setForeground(list.getSelectionForeground());
            } else {
                setBackground(list.getBackground());
                setForeground(list.getForeground());
                
            }
       
                      
            ImageIcon icon = images[selectedIndex];            
            setIcon(icon);
            if (icon != null) 
            	setFont(list.getFont());           
            	
            	
            return this;
        }

	
    }
}

